//用户vuex  数据模块
//解构ajax接口函数
import { checkLoginReq, getUserInfoReq } from '@/api/user'

const state = {
    //初始化 从本地拉取数据赋值给vuex
    token: localStorage.getItem('t_k'),
    role: localStorage.getItem('role'),
    userInfo: {}, //用户信息
}

//同步方法 同步修改数据
const mutations = {
    SET_TOKEN(state, data) {
        //token存vuex
        state.token = data

        //token存本地
        localStorage.setItem('t_k', data)
    },
    SET_ROLE(state, data) {
        state.role = data
        localStorage.setItem('role', data)
    },
    SET_USERINFO(state, data) {
        state.userInfo = data
    },
    A_CLEAR(state) {
        //清空vuex
        state.userInfo = {}
        state.token = ''
        state.role = ''

        //清空本地
        localStorage.clear()
    },
}
const actions = {
    //登录
    A_login({ commit }, data) {
        //凡是 actions里面有异步 必须包一层Promise壳子
        return new Promise(async resolve => {
            //发送请求
            let res = await checkLoginReq(data)
            let { code, msg, token, role } = res.data
            if (code === 0) {
                commit('SET_TOKEN', 'Bearer ' + token)
                commit('SET_ROLE', role)
                    //切换promise状态为 已成功
                resolve()
            }
        })
    },
    //获取个人信息
    A_getUserInfo({ commit }) {
        return new Promise(async(resolve, reject) => {
            // try {
            //     let res = await getUserInfoReq()
            //         //调用mutations里面的同步方法 存储数据到vuex中
            //     commit('SET_USERINFO', res.data)
            //     resolve()
            // } catch (error) {
            //     reject(errno)
            // }

            getUserInfoReq()
                .then(res => {
                    commit('SET_USERINFO', res.data)
                    resolve()
                })
                .catch(err => {
                    reject(err)
                })
        })

    },


    //清除个人信息
    A_clear({ commit }) {
        return new Promise(resolve => {
            commit('A_CLEAR')
            resolve()
        })
    },
}
export default {
    //命名空间
    namespaced: true,
    state,
    mutations,
    actions,
}